<?php

namespace app\uniapp\controller;

use app\common\exception\MiException;
use app\uniapp\middleware\CheckLogin;
use app\uniapp\service\UniAuthService;
use app\uniapp\service\UniReqService;
use app\uniapp\service\UserAddressService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\response\Json;

class UserAddressController extends UniController
{

    protected array $middleware = [
        CheckLogin::class,
    ];

    /**
     * @throws DbException
     */
    public function paginate(){
        return UniReqService::instance()->setService(UserAddressService::instance())->setPaginate()->getResponse();
    }

    /**
     * @throws MiException
     */
    public function add(Request $request){
        if ($request->isPost()){
            return UniReqService::instance()->setService(UserAddressService::instance())->add()->getResponse();
        }

    }

    /**
     * @throws MiException
     */
    public function edit(Request $request){
        if ($request->isPost()){
            return UniReqService::instance()->setService(UserAddressService::instance())->edit()->getResponse();
        }

    }

    /**
     * @return Json|void
     */
    public function find(){
        return UniReqService::instance()->setService(UserAddressService::instance())->setFind()->getResponse();
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function del(){
        return UniReqService::instance()->setService(UserAddressService::instance())->delete()->getResponse();
    }

    /**
     * 获取默认地址
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDefault(): Json
    {
        $info = UserAddressService::instance()->getDefault();
        return jsonSuccess([
            'info' => $info
        ]);
    }

    /**
     * 设置默认地址
     * @param Request $request
     * @return void
     */
    public function setDefault(Request $request){
        $id = $request->post('id');
        $uid = UniAuthService::instance()->getLoginId();
        $info = UserAddressService::instance()->update(['is_default'=>1], ['id'=>$id]);
        // 将其他的全部改为非默认
        UserAddressService::instance()->update(['is_default' => 0], [
            ['id','<>', $id],
            ['user_id', '=', $uid]
        ]);
        return jsonSuccess([
            'info' => $info
        ]);

    }

}
